/*
 * 
 * 
 * 
 */
package com.cms.template.directive;

import com.cms.entity.Category;
import com.cms.entity.Site;
import com.cms.service.CategoryService;
import com.cms.utils.FreeMarkerUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 模板指令 - 父栏目列表
 * 
 * 
 * 
 */
@Component
public class CategoryParentListDirective extends BaseDirective {

	@Autowired
	private CategoryService categoryService;

	/** "栏目ID"参数名称 */
	private static final String ID_PARAMETER_NAME = "id";

	/** "编码"参数名称 */
	private static final String CODE_PARAMETER_NAME = "code";
	
	/** "是否递归"参数名称 */
	private static final String RECURSIVE_PARAMETER_NAME = "recursive";

	/** 变量名称 */
	private static final String VARIABLE_NAME = "categorys";

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		Site currentSite = getCurrentSite();
	    Integer siteId = currentSite.getId();
	    Integer id = FreeMarkerUtils.getParameter(ID_PARAMETER_NAME, Integer.class, params);
		String code = FreeMarkerUtils.getParameter(CODE_PARAMETER_NAME, String.class, params);
		Boolean recursive = FreeMarkerUtils.getParameter(RECURSIVE_PARAMETER_NAME, Boolean.class, params);
		Integer start = getStart(params);
		Integer count = getCount(params);
		List<Category> categorys = categoryService.findParents(id,code, recursive != null ? recursive : false, start, count,siteId);
		setLocalVariable(VARIABLE_NAME, categorys, env, body);
	}
}